<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>ajax上传文件</title>
    <style type="text/css">
      form p {
        margin: 5px;
      }
    </style>
  </head>
  <body>
    <form>
      <p>
        <input id="ajaxFile" type="file" style="display: none;" onchange="fileChange(this)" />
        <input id="fileName" type="text" readonly />
        <button type="button" onclick="selectFile()">选择文件</button>
      </p>
      <p>
        <button type="button" onclick="ajaxUpload()">提交</button>
      </p>
    </form>

    <script src="./lib/jquery.min.js"></script>
    <script type="text/javascript">
      function selectFile() {
        $('#ajaxFile').click()
      }

      function fileChange(e) {
        var file = $(e).val()
        if (file != '') {
          var pos = file.lastIndexOf('\\')
          file = file.substring(pos + 1)
        }
        $('#fileName').val(file)
      }

      function ajaxUpload() {
        if (!$('#ajaxFile').val()) {
          alert('请选择文件!')
          return false
        }
        var fileext = ''
        var i = $('#ajaxFile').val().lastIndexOf('.')
        if (i > -1) {
          fileext = $('#ajaxFile').val().substring(i).toLowerCase()
        }
        if (fileext != '.jpg' && fileext != '.png') {
          alert('上传文件的格式需为.jpg或者.png!')
          return false
        }
        var file = $('#ajaxFile')[0].files[0]
        var fileSize = file.size //单位：b
        if (fileSize > 2 * 1024 * 1024) {
          alert('上传文件的大小限制在2M以内')
          return false
        }

        //利用formData对象ajax上传，IE10支持
        var formData = new FormData()
        formData.append('files', $('#ajaxFile')[0].files[0])
        $.ajax({
          url: '上传路径',
          type: 'POST',
          data: formData,
          processData: false,
          contentType: false,
          async: false,
          success: function (data) {
            alert(data)
          },
        })
      }
    </script>
  </body>
</html>
